<template>
  <div class="common">
    <div class="action">
      <el-button type="primary" @click="back">返回</el-button>
      <el-button type="primary" @click="save(elFormRef)">保存</el-button>
    </div>
    <div class="info">
      <el-form ref="elFormRef" :rules="rules" :model="formData">
        <div style="display: flex">
          <el-form-item label="模板名称：" style="margin-right: 30px" prop="id">
            <el-select class="selectStyle" @change="showForm" v-model="formData.id" placeholder="请选择安全档案模板">
              <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单位类型" prop="unitType">
            <el-select class="selectStyle" v-model="formData.unitType" placeholder="自动填充模板关联的外部单位类型" disabled></el-select>
          </el-form-item>
        </div>
        <div>
          <div class="rowData">
            <el-form-item label="单位编号：" class="inputStyle" prop="unitNumber" >
              <el-input v-model="formData.unitNumber"></el-input>
            </el-form-item>
            <el-form-item label="单位名称：" class="inputStyle" prop="unitName" label-width="140px">
              <el-input v-model="formData.unitName"></el-input>
            </el-form-item>
            <el-form-item label="驻场房间编号：" class="inputStyle" prop="roomNumber" label-width="140px">
              <el-input v-model="formData.roomNumber"></el-input>
            </el-form-item>
          </div>
          <div class="rowData">
            <el-form-item label="负责人：" class="inputStyle" prop="headName" label-width="94px">
              <el-input v-model="formData.headName"></el-input>
            </el-form-item>
            <el-form-item label="负责人电话：" class="inputStyle" prop="headPhone" label-width="140px">
              <el-input v-model="formData.headPhone"></el-input>
            </el-form-item>
            <div class="inputStyle">
              <el-form-item label="是否考核：" class="inputStyle" prop="isAssess" label-width="140px">
                <el-radio-group v-model="formData.isAssess">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <div v-show="formVisible">
        <v-form-render :form-json="vFormJson" :form-data="vFormData" :option-data="vOptionData" ref="vFormRef">
        </v-form-render>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, onBeforeMount, nextTick, onBeforeUpdate } from "vue";
import {addSave, editSave} from "@/api/secure/securityUnit";
import {ElMessage} from "element-plus";
import { getList } from "@/api/secure/securityUnit";
const formData = ref({
  unitTemplateName: '',
  unitType: '',
  id: '',
  catalogueId: '',
  unitNumber: '',
  unitName: '',
  roomNumber: '',
  headName: '',
  headPhone: '',
  isAssess: '',
  formJson: '',
  dataJson: '',
  createUserId: ''
})

let vFormJson = reactive({})
const vFormData = reactive({})
const vOptionData = reactive({})
const vFormRef = ref(null)
const formVisible = ref(false)
const elFormRef = ref()
const validatorPhone = (rule: any, value: any, callback: any) => {
  if (!value) return callback(new Error('请输入联系电话！'))
  if (value && !/^1[3|4|5|7|8|9][0-9]\d{8}$/.test(value)) return callback(new Error('电话号码格式不正确！'))
  callback()
}
const rules = ref({
  model: {
    required: true,
    message: '请选择安全档案模板',
    trigger: 'change'
  },
  catalogueName: {
    required: true,
    message: '请选择单位类型',
    trigger: 'change'
  },
  unitNumber: {
    required: true,
    message: '请输入单位编号',
    trigger: 'blur'
  },
  unitName: {
    required: true,
    message: '请输入单位名称',
    trigger: 'blur'
  },
  roomNumber: {
    required: true,
    message: '请输入驻场房间编号',
    trigger: 'blur'
  },
  headName: {
    required: true,
    message: '请输入负责人',
  },
  headPhone: {
    required: true,
    message: '电话号码格式不正确',
    validator: validatorPhone,
    trigger: 'change'
  },
  isAssess: {
    required: true,
    message: '请选择是否考核',
  }
});
const emit = defineEmits(["getValue"]);
const props = defineProps({
  list: {
    type: Array,
    default: () => [],
  }
})
//获取登录信息
const createUserId = () => {
  console.log('获取createUserId')
  const login: any = JSON.parse(localStorage.getItem('CacheState'))
  // console.log('login', login.user.userInfo);
  formData.value.createUserId = login.user.userInfo.userId
}

onBeforeUpdate(() => {
  // createUserId()
})
/**
 * 返回，回到index
 */
const back = () => {
  emit("getValue",'index')
};
const list = ref([])
const models = ref([])
const  options= ref([])
getList().then(res => {
    console.log(res);
      list.value = res
      console.log(list.value);
      for(let i=0;i<list.value.length;i++){
        let obj = {value:'',label:''}
        let obj1= {mode:'',catalogueName:''}
        obj.value = list.value[i].templateName
        obj.label = list.value[i].templateName
        obj1.mode = list.value[i].templateName
        obj1.catalogueName = list.value[i].unitType
        options.value.push(obj)
        models.value.push(obj1)
      }
      console.log(options);
      console.log(models);
      
  })
/**
 * 保存，回到index
 */
const save = async (formEl: any) => {
  console.log('add')
  await formEl.validate(async (valid: any) => {
    if (valid) {
      vFormRef.value.getFormData().then(res => {
        formData.value.formJson = JSON.stringify(vFormJson)
        formData.value.dataJson = JSON.stringify(res)
        console.log('formData.value')
        console.log(formData.value)
        const data = ref({})
        data.value.unitTemplateName = formData.value.id
        data.value.unitType = formData.value.unitType
        data.value.unitNumber = formData.value.unitNumber
        data.value.unitName = formData.value.unitName
        data.value.headName = formData.value.headName
        data.value.headPhone = formData.value.headPhone
        data.value.roomNumber = formData.value.roomNumber
        data.value.examine = formData.value.isAssess
        data.value.recycle = '1'
        console.log(formData.value.isAssess===1);
        addSave(data.value)
          .then(res => {
            ElMessage.success('保存成功')
            back()
          }).catch((err: any) => {
          ElMessage.error(err.message)
        })
      })
    }
  })
};
const showForm = () => {
  console.log(formData.value.id);
  
  let select = models.value.find(item => item.mode === formData.value.id);
  // vFormRef.value.setFormJson(select.formJson)
  console.log(select);
  
  formData.value.unitType = select.catalogueName
  formData.value.catalogueId = select.catalogueId
  formData.value.modelId = select.modelId
};


</script>

<style scoped>
  .common{
    padding: 40px 100px;
    height: 100%;
    margin: 10px;
    background-color: #FFFFFF;
  }
  .action{
    float: right;
    position: relative;
  }
  .line{
    border-top: 1px solid #1caad5;
    margin-top: 40px;
    margin-bottom: 20px;
  }
  .info{

  }
  .rowData{
    display: flex;
    margin-top: 20px;
  }
  .selectStyle{
    width: 300px;
  }
  .inputStyle{
    width: 450px;
  }
  .fileUpload{
    width: 100px;
    height: 30px;
    border: 1px solid var(--el-border-color);
    border-radius: 5px;
    color: #5a5756;
    text-align: center;
  }

  .el-input{
    width: 300px;
  }
</style>
